`
https://leetcode.cn/problems/subsets-ii/
`

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsetsWithDup = function (nums) {
  const res = []
  const track = []

  // 预先排序，让相邻的元素挨在一起，方便剪枝
  // 两条值相同的相邻树枝会产生重复，所以需要剪枝
  nums.sort((a, b) => a - b)

  const backtrack = (start) => {
    res.push([...track])

    for (let i = start; i < nums.length; i++) {
      // 剪枝逻辑，值相同的相邻树枝，只剪掉遇到的第一条
      if (i > start && nums[i] === nums[i - 1]) continue

      track.push(nums[i])
      backtrack(i + 1)
      track.pop()
    }
  }

  backtrack(0)

  return res
};